package com.dajie.pt.service;

import com.dajie.core.profile.ProfileServicesContext;
import com.dajie.core.profile.enums.ComputedIdentityEnum;
import com.dajie.core.profile.model.Education;
import com.dajie.core.profile.model.UserDetail;
import com.dajie.core.profile.model.UserIdentity;
import com.dajie.core.profile.service.ComputedIdentityService;
import com.dajie.core.profile.service.ProfileService;
import com.dajie.corp.api.CorpServicesContext;
import com.dajie.corp.api.service.CorpProjectInvitationService;
import com.dajie.corp.api.service.CorpProjectService;
import com.dajie.corp.api.service.CorpService;
import com.dajie.corp.biz.project.model.ClubProject;
import com.dajie.corp.enums.common.ClubInvitationSourceEnum;
import com.dajie.corp.info.model.CorpBase;
import com.dajie.guanke.GuankeServiceContext;
import com.dajie.guanke.service.UserAccountService;
import com.dajie.infra.user.InfraUserServiceContext;
import com.dajie.infra.user.model.UserBase;
import com.dajie.infra.user.model.UserPhone;
import com.dajie.infra.user.service.UserBaseService;
import com.dajie.pt.job.api.InvitationServicesContext;
import com.dajie.pt.service.utils.CommonUtil;
import com.dajie.sms.SmsServicesContext;
import com.dajie.sms.service.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * author:yunbin.an
 * create_date:2014-10-11
 */

public class RegisterNotLoad {
    private static Logger logger = LoggerFactory.getLogger(RegisterNotLoad.class);
    private static SmsService smsService = SmsServicesContext.getInstance().getSmsService();
    public static final UserBaseService userService = InfraUserServiceContext.getInstance().getUserService();
    public static final ProfileService profileService = ProfileServicesContext.getInstance().getProfileService();
    public static final UserAccountService userAccountService = GuankeServiceContext.getInstance().getUserAccountService();
    public static final CorpProjectInvitationService corpProjectInvitationService = InvitationServicesContext.getInstance().getCorpProjectInvitationService();
    public static final CorpProjectService cpservice = CorpServicesContext.getInstance().getCorpProjectService();
    public static final ComputedIdentityService computedIdentityService = ProfileServicesContext.getInstance().getComputedIdentityService();
    private static Connection connTBUser = null;
    private static Connection connTBMail = null;
    private static Connection connTBClub = null;
    public Pattern pattern = Pattern.compile("^1\\d{10}$");

    private static Calendar calendar = Calendar.getInstance();
    public static final int FGTYPE = 3000;
    public static final int TYPE = 3000;
    public static final int TPL = 408;
    public static final int TPL_BL = 422;
    public static final int TPL_ZBL = 421;

    public String sendSms(int type, int tpl, Map map) {
        String result = smsService.sendSMS(type, tpl, map).getResult();
        //logger.error("sendSms --> send sms type:{} tpl:{} mobile:{} result:{}", type, tpl, map.get("MOBILE"), result);
        return result;
    }

    public RegisterNotLoad() {
        //设置应届生毕业年份: 1-6月 取当前年份  7-12月取当前年份+1
        if (calendar.get(Calendar.MONTH) < 6)
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
        else
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR + 1));
    }

    public synchronized Connection getInstanceConnTBUser() {
        if (connTBUser == null) {
            connTBUser = getConn_DBUSER();
            return connTBUser;
        }
        return connTBUser;
    }

    public synchronized Connection getInstanceConnTBMail() {
        if (connTBMail == null) {
            connTBMail = getConn_MAIL();
            return connTBMail;
        }
        return connTBMail;
    }

    public synchronized Connection getInstanceConnTBClub() {
        if (connTBClub == null) {
            connTBClub = getConn_CLUB();
            return connTBClub;
        }
        return connTBClub;
    }


    public String getMobile(int uid) {
        String mobile = null;
        UserPhone userPhone = userService.getDefaultPhoneByUid(uid);
        UserDetail userDetail1 = profileService.getUserDetailByUid(uid);
        if (userPhone == null) {
            mobile = userDetail1.getMobile();
        } else {
            mobile = userPhone.getPhoneNumber();
        }
        if (mobile.contains("-")) {
            String[] t_mobile = mobile.split("-");
            if (t_mobile.length > 1) {
                mobile = mobile.split("-")[1];
            }
        }
        return mobile;
    }

    public Connection getConn_DBUSER() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:cobar://cobarvip:12001/DB_USER_PT?autoCommit=true&autoReconnect=true&useUnicode=true&tinyInt1isBit=false&zeroDateTimeBehavior=round&characterEncoding=UTF-8&yearIsDateType=false&zeroDateTimeBehavior=convertToNull";
        String user = "platformol";
        String password = "platformol-3";
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (ClassNotFoundException e) {
            logger.error(e.toString());
        } catch (SQLException e) {
            logger.error(e.toString());
        }
        return null;
    }

    public Connection getConn_MAIL() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:cobar://cobarvip:12001/DB_MAIL?autoCommit=true&autoReconnect=true&useUnicode=true&tinyInt1isBit=false&zeroDateTimeBehavior=round&characterEncoding=UTF-8&yearIsDateType=false&zeroDateTimeBehavior=convertToNull";
        String user = "platformol";
        String password = "platformol-3";
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (ClassNotFoundException e) {
            logger.error(e.toString());
        } catch (SQLException e) {
            logger.error(e.toString());
        }
        return null;
    }

    public Connection getConn_CLUB() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://db_querys_3:3309/DB_CLUB?autoCommit=true&autoReconnect=true&useUnicode=true&tinyInt1isBit=false&zeroDateTimeBehavior=round&characterEncoding=UTF-8&yearIsDateType=false&zeroDateTimeBehavior=convertToNull";
        String user = "platform_sel";
        String password = "dajie.platform)-";
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (ClassNotFoundException e) {
            logger.error(e.toString());
        } catch (SQLException e) {
            logger.error(e.toString());
        }
        return null;
    }


    public void closeConnAll() {
        try {
            this.getConn_DBUSER().close();
            this.getConn_MAIL().close();
            this.getConn_CLUB().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //获取指定时间范围的新注册用户
    public List<Integer> getUidFromUser(String start_time, String end_time) {
        List<Integer> uids = new ArrayList();
        Statement statement = null;
        ResultSet rs = null;
        //String t_sql = "SELECT u.uid FROM tb_user_base u, tb_user_phone p WHERE u.uid = p.uid AND u.create_date >= %s AND u.create_date < %s AND u.status = 9 AND u.reg_type = 2 AND p.type = 3;";
        String t_sql = "SELECT u.uid FROM tb_user_base u, tb_user_phone p WHERE u.uid = p.uid AND u.create_date >= %s AND u.create_date < %s AND u.status = 9 AND p.type = 3;";
        String sql = String.format(t_sql, start_time, end_time);
        Connection conn = getInstanceConnTBUser();
        try {
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                int uid = rs.getInt(1);
                if (userAccountService.selectUserId(uid) == null) {
                    if (!isSendUid(uid)) {
                        uids.add(rs.getInt(1));
                    } else {
                        logger.error("getUidFromUser --> uid is exist tb_djgk:{}", uid);
                    }

                } else {
                    logger.error("getUidFromUser --> uid is loaded  uid:{}", uid);
                }

            }
            logger.error("getUidFromUser --> load uid size:{}", uids.size());
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statement.close();
                connTBUser.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return uids;
    }

    //为用户添加邀约 批量
    public void addInviteForUser(List<Integer> uids, int infoId) {
        List<Integer> t_uids = new ArrayList();
        for (int i = 0; i < uids.size(); i++) {
            t_uids.add(uids.get(i));
            if ((i + 1) % 100 == 0) {
                boolean flag = corpProjectInvitationService.createProjectInvitation(t_uids, infoId, ClubInvitationSourceEnum.AD);
                logger.error("send invite to uids --> uid:{} infoId:{} result:{}", uids.toString(), infoId, flag);
                t_uids.clear();
            }
        }
        if (!t_uids.isEmpty()) {
            boolean flag = corpProjectInvitationService.createProjectInvitation(t_uids, infoId, ClubInvitationSourceEnum.AD);
            logger.error("send invite to uids --> uid:{} infoId:{} result:{}", uids.toString(), infoId, flag);
            t_uids.clear();
        }

    }

    //发送成功后 将UID插入数据库 数据交界去重
    public int insertUid(int uid) {
        Statement statement = null;
        ResultSet rs = null;
        int result = 0;
        String t_sql = "insert into tb_djgk_uid (uid,create_date) values (%s,%s)";
        String sql = String.format(t_sql, uid, "now()");
        Connection connection = getInstanceConnTBMail();
        try {
            statement = connection.createStatement();
            result = statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //判断该用户是否已经发送过短信 数据交界去重
    public boolean isSendUid(int uid) {
        Statement statement = null;
        ResultSet rs = null;
        int result = 0;
        String t_sql = "select count(*) from tb_djgk_uid where uid = %s";
        String sql = String.format(t_sql, uid, uid);
        Connection connection = getInstanceConnTBMail();
        try {
            statement = connection.createStatement();
            rs = statement.executeQuery(sql);
            if (rs.next()) {
                result = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    rs.close();
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        if (result > 0) {
            return true;
        } else {
            return false;
        }

    }

    //获取量最大的两个项目ID
    public List<Integer> getMaxProjectId() {
        List<Integer> projectId = new ArrayList();
        Statement statement = null;
        ResultSet rs = null;
        Connection connection = getInstanceConnTBClub();
        String sql = "select a.project_id from  (select project_id,count(1) total from tb_club_project_invitation where create_date>=date_sub(curdate(),interval 5 day)  group by project_id order by count(1) desc) a limit 2";
        try {
            statement = connection.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                projectId.add(rs.getInt(1));
            }
            logger.error("getMaxProjectId --> projectIds:{}", projectId.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return projectId;
    }

    //根据项目ID获取邀约ID
    public int getProjectInvitationInfoIdByProjectId(int projectId) {
        Statement statement = null;
        ResultSet rs = null;
        String t_sql = "select id from tb_club_project_invitation_info where project_id = %s;";
        String sql = String.format(t_sql, projectId);
        Connection connection = getInstanceConnTBClub();
        int infoId = 0;
        try {
            statement = connection.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                infoId = rs.getInt(1);
                logger.error("get infoId --> infoId:{}", rs.getInt(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return infoId;
    }

    public int getIdentityByUid(int uid) {
        /**
         * 1：白领
         * 2：准白领
         * 3：应届生
         * 4：非应届生
         **/
        ComputedIdentityEnum computedIdentityEnum = computedIdentityService.getIdentity(uid);
        logger.error("identity --> uid:{} identity:{}", uid, computedIdentityEnum.getCode());
        return computedIdentityEnum.getCode();
    }

    public String getUserSchool(int uid) {
        String school = null;
        Education education = profileService.getHighestEducationByUid(uid);
        if (education != null) {
            school = education.getSchoolName();
        }
        return school;
    }

    public String getUserName(int uid) {
        String name = null;
        UserBase userBase = userService.getUserByUid(uid);
        if (userBase != null) {
            name = userBase.getName();
        }
        return name;
    }

    public String getUserMajor(int uid) {
        String major = null;
        Education education = profileService.getHighestEducationByUid(uid);
        if (education != null) {
            major = education.getMajorName();
        }
        return major;
    }

    //根据项目ID获取该公司名称
    public String getCorpNameByProjectId(int projectId) {
        String corpName = "";
        ClubProject clubProject = cpservice.findById(projectId);
        String cid = clubProject.getCid();
        CorpService cp = CorpServicesContext.getInstance().getCorpService();
        CorpBase corpBase = cp.getCorpBaseByCid(cid);
        if (corpBase != null) {
            corpName = corpBase.getName();
        }
        return corpName;
    }

    public static void main(String[] args) {
        logger.error("args size:{}", args.length);
        if (args.length != 2) {
            logger.error("args length error");
            System.exit(0);
        }
        String start_time = args[0];
        String end_time = args[1];
        logger.error("main --> input args start_time:{} end_time:{} ", start_time, end_time);
        RegisterNotLoad registerNotLoad = new RegisterNotLoad();
        List<Integer> uids = registerNotLoad.getUidFromUser(start_time, end_time);
        String contArgs1 = null;
        String contArgs2 = null;

        // statr 获取应届生
        List<Integer> freshGraduate = new ArrayList();
        for (int i = 0; i < uids.size(); i++) {
            if (registerNotLoad.getIdentityByUid(uids.get(i)) == 3) {
                freshGraduate.add(uids.get(i));
            }
        }
        logger.error("main --> freshGraduate size:{} uids:{}", freshGraduate.size(), freshGraduate.toString());
        // end 获取应届生

        List<Integer> projectId = registerNotLoad.getMaxProjectId();  //获取项目ID

        // start 根据项目ID 获取项目邀约ID 为用户添加项目邀约 生成短信参数
        if (freshGraduate != null && projectId != null && projectId.size() >= 2) {
            for (int i = 0; i < projectId.size(); i++) {
                registerNotLoad.addInviteForUser(freshGraduate, registerNotLoad.getProjectInvitationInfoIdByProjectId(projectId.get(i)));  //创建项目邀约
            }
            contArgs1 = registerNotLoad.getCorpNameByProjectId(projectId.get(0));
            logger.error("main --> contArgs1 --> contArgs1:{}", contArgs1);
            contArgs2 = registerNotLoad.getCorpNameByProjectId(projectId.get(1));
            logger.error("main --> contArgs2 --> contArgs2:{}", contArgs2);
        } else {
            logger.error("main --> project count less 2 --> project size:{}", projectId.toString());
        }
        // end  根据项目ID 获取项目邀约ID 为用户添加项目邀约 生成短信参数

        if (uids != null && uids.size() > 0) {
            for (int i = 0; i < uids.size(); i++) {
                int uid = uids.get(i);
                String mobile = registerNotLoad.getMobile(uid);
                if (mobile != null && !"".equals(mobile)) {
                    Map<String, String> map = new HashMap();
                    String result = "0";
                    int identity = registerNotLoad.getIdentityByUid(uid);
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
                    String st = format.format(new Date());
                    String userName = "";
                    String userMajor = "";
                    switch (identity) {
                        case 1:
                            //白领
                            map.put("MOBILE", mobile);
                            map.put("MYURL", "http://www.dajie.com/app/phone/download?id=8&identity=" + identity + "&gallery=guodu&signature=dajie&ch=registerNotLoad" + TPL_BL + "&st=" + st + "&sms_uid=" + uid);
                            userName = registerNotLoad.getUserName(uid);
                            userMajor = registerNotLoad.getUserMajor(uid);
                            if (userName == null || "".equals(userName)) {
                                continue;
                            }
                            map.put("UNAME", userName);
                            if (userMajor != null && !"".equals(userMajor)) {
                                map.put("majorname", userMajor);
                            } else {
                                map.put("majorname", "同专业");
                            }
                            result = registerNotLoad.sendSms(TYPE, TPL_BL, map);
                            logger.error("send --> uid:{} identity:{} tpl:{} mobile:{} result:{}", uid, identity, TPL_BL, mobile, result);
                            break;
                        case 2:
                            //准白领
                            map.put("MOBILE", mobile);
                            map.put("MYURL", "http://www.dajie.com/app/phone/download?id=8&identity=" + identity + "&gallery=guodu&signature=dajie&ch=registerNotLoad" + TPL_ZBL + "&st=" + st + "&sms_uid=" + uid);
                            userName = registerNotLoad.getUserName(uid);
                            userMajor = registerNotLoad.getUserMajor(uid);
                            if (userName == null || "".equals(userName)) {
                                continue;
                            }
                            map.put("UNAME", userName);
                            if (userMajor != null && !"".equals(userMajor)) {
                                map.put("majorname", userMajor);
                            } else {
                                map.put("majorname", "同专业");
                            }
                            result = registerNotLoad.sendSms(TYPE, TPL_ZBL, map);
                            logger.error("send --> uid:{} identity:{} tpl:{} mobile:{} result:{}", uid, identity, TPL_ZBL, mobile, result);
                            break;
                        case 3:
                            //应届生
                            int f_tpl = 405;
                            map.put("MOBILE", mobile);
                            if (f_tpl == 405) {
                                map.put("contArgs1", contArgs1);
                                map.put("contArgs2", contArgs2);
                                map.put("MYURL", "http://www.dajie.com/app/phone/download?id=7&identity=" + identity + "&gallery=guodu&signature=dajie&ch=registerNotLoad" + f_tpl + "&st=" + st + "&sms_uid=" + uid);
                            } else {
                                map.put("uname", CommonUtil.getUnameByUid(uid));
                                map.put("smsUrl", "http://www.dajie.com/app/phone/download?id=30&identity=" + identity + "&tpl=" + f_tpl + "&uid=" + uid);
                            }
                            result = registerNotLoad.sendSms(FGTYPE, f_tpl, map);
                            logger.error("send --> uid:{} identity:{} tpl:{} mobile:{} result:{}", uid, identity, f_tpl, mobile, result);
                            break;
                        case 4:
                            //非应届生
                            map.put("MOBILE", mobile);
                            map.put("MYURL", "http://www.dajie.com/app/phone/download?id=8&identity=" + identity + "&gallery=guodu&signature=dajie&ch=registerNotLoad" + TPL + "&st=" + st + "&sms_uid=" + uid);
                            result = registerNotLoad.sendSms(TYPE, TPL, map);
                            logger.error("send --> uid:{} identity:{} tpl:{} mobile:{} result:{}", uid, identity, TPL, mobile, result);
                            break;
                        default:
                            //其他
                            map.put("MOBILE", mobile);
                            map.put("MYURL", "http://www.dajie.com/app/phone/download?id=8&identity=" + identity + "&gallery=guodu&signature=dajie&ch=registerNotLoad" + TPL + "&st=" + st + "&sms_uid=" + uid);
                            result = registerNotLoad.sendSms(TYPE, TPL, map);
                            logger.error("send --> uid:{} identity:{} tpl:{} mobile:{} result:{}", uid, identity, TPL, mobile, result);
                            break;
                    }
                    if (Integer.parseInt(result) > 0) {
                        registerNotLoad.insertUid(uid);
                    }
                } else {
                    logger.error("main --> uid mobile not exit --> uid:{}", uid);
                }
            }
        }
        registerNotLoad.closeConnAll();
    }
}
